from django.conf import settings

from apscheduler.schedulers.background import BackgroundScheduler

from scheduler.jobstores import DjangoJobStore, register_job
from scheduler.models import DjangoJob, DjangoJobExecution
from data.utils import sync_guizhou_purchases


try:
    DjangoJobExecution.objects.all().delete()
    DjangoJob.objects.all().delete()
    scheduler = BackgroundScheduler()
    scheduler.add_jobstore(DjangoJobStore(), 'default')

    if settings.SYNC_CONFIG.get('ENABLE', True):
        @register_job(
            scheduler,
            'cron',
            hour=int(settings.SYNC_CONFIG.get('TIME', '24:00').split(':')[0]),
            minute=int(settings.SYNC_CONFIG.get('TIME', '24:00').split(':')[1]),
            id='定时查询采购信息任务',
            max_instances=400
        )
        def purchase_query():
            sync_guizhou_purchases()
    else:
        print('自动同步已禁用')

    scheduler.start()
except Exception as e:
    print(e)



